package com.alipay.app.groupmeal.standard.ui.b.util;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.Ndef;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcV;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import java.io.IOException;
import java.lang.ref.WeakReference;

public class NFCManager {
    private static final String TAG = "dxp.NFCManager";

    private WeakReference<Activity> mActivity;
    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mIntentFilter = null;
    private String[][] mTechList = null;

    private OnReceiveNfcTagCallback mCallback;

    public interface OnReceiveNfcTagCallback {
        void onReceiveNfcTag(String tag);
    }

    // 初始化
    public NFCManager(Activity activity) {
        mActivity = new WeakReference<>(activity);
        mCallback = (OnReceiveNfcTagCallback) activity;

        mAdapter = NfcAdapter.getDefaultAdapter(mActivity.get());
        if (mAdapter == null) {
            Toast.makeText(mActivity.get(), "设备不支持NFC功能!", Toast.LENGTH_SHORT).show();
            return;
        } else {
            if (!mAdapter.isEnabled()) {
                isToSet();
                return;
            } else {
//                Toast.makeText(mActivity.get(), "NFC功能已打开!", Toast.LENGTH_SHORT).show();
            }
        }

        // 配置pendingIntent，NFC系统在读卡后会通过该配置跳转至目标Activity
        Intent intent = new Intent(mActivity.get(), mActivity.get().getClass());
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        mPendingIntent = PendingIntent.getActivity(mActivity.get(), 0, intent, 0);
        // 做一个IntentFilter过滤你想要的action 这里过滤的是ndef
        IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        try {
            filter.addDataType("*/*");
        } catch (IntentFilter.MalformedMimeTypeException e) {
            e.printStackTrace();
        }
        mTechList = new String[][]{
                {IsoDep.class.getName(), NfcA.class.getName()},
                {MifareClassic.class.getName(), NfcA.class.getName()},
                {MifareClassic.class.getName()},
                {Ndef.class.getName()},
                {NfcV.class.getName()}
        };
        mIntentFilter = new IntentFilter[]{filter};
     }

    // 注册前台分发
    public void dispatch() {
        Log.d(TAG, "dispatch");
        if (mAdapter == null) {
            Log.w(TAG, "mAdapter is null");
            return;
        }
        try {
            mAdapter.enableForegroundDispatch(mActivity.get(), mPendingIntent, mIntentFilter, mTechList);
        } catch (Throwable e) {
            Log.e(TAG, "enableForegroundDispatch exception:" + e);
            e.printStackTrace();
        }
    }

    // 取消前台分发
    public void cancelDispatch() {
        Log.d(TAG, "cancelDispatch");
        if (mAdapter == null) {
            Log.w(TAG, "mAdapter is null");
            return;
        }
        if(mActivity.get() != null && !(mActivity.get().isDestroyed() || mActivity.get().isFinishing())){
            mAdapter.disableForegroundDispatch(mActivity.get());
        }
    }

    // 处理Intent，解析NFC标签
    public void receiveTag(Intent intent) {
        Log.w(TAG, "receiveTag : " + intent.getAction());

        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        //获取 Tag 读取 ID 得到字节数组 转字符串 转码 得到卡号（默认16进制 这请自便）
        if (tag == null) {
            Log.w(TAG, "tag is null !!");
            return;
        }

//        String tagId = toHexString(tag.getId());
        byte[] cardsn = new byte[4];
        byte[] temp = tag.getId();
        for (int i = 0; i < 4; i++) {
            cardsn[3 - i] = temp[i];
        }
        String tagId = toHexString(cardsn);
        Log.i(TAG, "tagId = " + tagId);
        mCallback.onReceiveNfcTag(tagId);

        String[] techList = tag.getTechList();
        if (techList != null) {
            for (String tech : techList) {
                Log.d(TAG, "tech = " + tech);
            }
        }


        if (intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED) ||
                intent.getAction().equals(NfcAdapter.ACTION_TECH_DISCOVERED)) {
            Log.d(TAG, "start read nfc tag");
            Ndef ndef = Ndef.get(tag);
            if (ndef == null) {
                Log.w(TAG, "NDEF is null");
                MifareClassic m1 = MifareClassic.get(tag);
                if (m1 == null) {
                    Log.w(TAG, "M1 is null");
                    IsoDep isoDep = IsoDep.get(tag);
                    if(isoDep == null){
                        NfcV nfcV = NfcV.get(tag);
                        if(nfcV != null){
                            Log.i(TAG, "tag is NfcV !");
                        } else {
                            Log.w(TAG, "continue matching ... ");
                        }
                    } else {
                        Log.i(TAG, "cpu connect");
                    }

                } else {
                    // read M1
                    Log.i(TAG, "read M1");
                    String nfcType = "";
                    switch (m1.getType()) {
                        case MifareClassic.TYPE_CLASSIC:
                            nfcType = "TYPE_CLASSIC";
                            break;
                        case MifareClassic.TYPE_PLUS:
                            nfcType = "TYPE_PLUS";
                            break;
                        case MifareClassic.TYPE_PRO:
                            nfcType = "TYPE_PRO";
                            break;
                        case MifareClassic.TYPE_UNKNOWN:
                            nfcType = "TYPE_UNKNOWN";
                    }
                    // 扇区数量
                    int sectorCount = m1.getSectorCount();
                    // block数量
                    int blockCount = m1.getBlockCount();
                    // 存储空间
                    int size = m1.getSize();
                    Log.i(TAG, "nfcType = " + nfcType + " | sectorCount = " + sectorCount + " | blockCount = " + blockCount + " | size = " + size);

                    int sectorIndex = 0;
                    try {
                        m1.connect();
                        boolean auth = m1.authenticateSectorWithKeyA(sectorIndex, MifareClassic.KEY_DEFAULT);
                        if (!auth) {
                            auth = m1.authenticateSectorWithKeyA(sectorIndex, MifareClassic.KEY_NFC_FORUM);
                        }
                        if (!auth) {
                            auth = m1.authenticateSectorWithKeyA(sectorIndex, MifareClassic.KEY_NFC_FORUM);
                        }
                        if (!auth) {
                            Log.w(TAG, "m1 auth fail");
                        }

                        int blockIndex = m1.sectorToBlock(sectorIndex);
                        byte[] blockData = m1.readBlock(blockIndex);
                        Log.i(TAG, "sector 1 , block data is " + toHexString(blockData));


                    } catch (IOException e) {
                        Log.e(TAG, "read m1 error! " + e.getMessage());
                        e.printStackTrace();
                    }

                }
            } else {
                // read NDEF
                Log.i(TAG, "read NDEF");
            }

        }


    }


    private void isToSet() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity.get());
        builder.setMessage("是否跳转到设置页面打开NFC功能");
//        builder.setTitle("提示");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                goToSet(mActivity.get());
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    private static void goToSet(Activity activity) {
        // 进入设置系统应用权限界面
        Intent intent = new Intent(Settings.ACTION_SETTINGS);
        activity.startActivity(intent);
    }


    /**
     * 将字节数组转换为字符串
     */
    private static String toHexString(byte[] inarray) {
        int i, j, in;
        String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
        String out = "";

        for (j = 0; j < inarray.length; ++j) {
            in = (int) inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }
        return out;
    }

    public void onDestroy() {
        Log.d(TAG, "onDestroy");
        mAdapter = null;
        mActivity.clear();
        mActivity = null;
    }

}
